package mymatrix;


import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import comm.ClientPriority;

import client.Client;

public class MatrixClient extends Client {
	private final int size = 1024;

	private final int jobs = 200;

	private long[][] matrix = new long[size][size];

	public MatrixClient(ClientPriority priority, int problemNumber,
			int version, String masterAddress, int masterPort,
			String codeServerAddress, int codeServerPort) {
		super(priority, problemNumber, version, masterAddress, masterPort,
				codeServerAddress, codeServerPort);
		// TODO Auto-generated constructor stub
	}

	private void populate(){
		for(int i = 0;i<this.size;i++){
			for(int j = 0;j<this.size;j++){
				this.matrix[i][j] = i*j+1;
			}
		}

	}

	public void execute() {

		populate();

		long ini = System.currentTimeMillis();
		int delta = this.size/jobs;


		for(int i = 0;i<jobs;i++){
			MatrixTask mt = new MatrixTask(i, size, matrix, matrix,delta*i,(delta)*(i+1));
			System.out.println("Delta:"+delta);
			commit(mt);
		}

		long total[][] = new long[size][size];
		System.out.println("Waiting:");
		for(int i = 0;i<jobs;i++){
			MyResult mr = ((MyResult) (getNextResult()));
			long result[][] = mr.getValue();
			int init =  mr.getIni();
			int end =  mr.getEnd();
			for(int x=init;x<end;x++){
				for(int y=0;y<this.size;y++){
					total[x][y] = result[x][y];

				}
			}


		}
		long end = System.currentTimeMillis() - ini;
		doLogTask("matrix.log", " Time: "+end+" size:"+size+" jobs"+jobs+"\n");
		System.out.println("Tempo de calculo:"+end);

		//			for(int x = 0;x<this.size;x++){
		//				for(int y = 0;y<this.size;y++){
		//					System.out.print(" "+total[x][y]);
		//				}
		//				System.out.println();
		//			}
		System.exit(0);
	}

	private void doLogTask(String filename, String taskinfo) {
		FileOutputStream file;
		try {
			file = new FileOutputStream(filename, true);
			DataOutputStream out = new DataOutputStream(file);
			out.writeBytes(taskinfo);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
		new MatrixClient(ClientPriority.NORMAL, 1, 1, "localhost", 0, "localhost", 0).execute();
	}

}
